package com.dyc.course.sys.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dyc.course.sys.entity.SysRoleEntity;
import com.dyc.course.sys.mapper.SysRoleDeptMapper;
import com.dyc.course.sys.mapper.SysRoleMenuMapper;
import com.dyc.course.sys.mapper.SysUserRoleMapper;
import com.dyc.course.sys.repository.SysRoleRepository;
import com.dyc.course.sys.service.SysRoleDeptService;
import com.dyc.course.sys.service.SysRoleMenuService;
import com.dyc.course.sys.service.SysRoleService;

import java.util.Date;

/**
 * 角色
 *
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	private SysRoleRepository repository;
	
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	
	@Autowired
	private SysRoleDeptService sysRoleDeptService;
	
	@Autowired
	private SysUserRoleMapper sysUserRoleRepository;
	
	@Autowired
	private SysRoleMenuMapper sysRoleMenuRepository;

	@Autowired
	private SysRoleDeptMapper sysRoleDeptRepository;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveRole(SysRoleEntity role) {
		role.setCreateTime(new Date());
		repository.save(role);

		//保存角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

		//保存角色与部门关系
		sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysRoleEntity role) {
		repository.save(role);

		//更新角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

		//保存角色与部门关系
		sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] roleIds) {
		//删除角色
		for (Long id : roleIds) {
			repository.deleteById(id);
		}

		//删除角色与菜单关联
		sysRoleMenuRepository.deleteBatch(roleIds);

		//删除角色与部门关联
		sysRoleDeptRepository.deleteBatch(roleIds);

		//删除角色与用户关联
		sysUserRoleRepository.deleteBatch(roleIds);
	}


}
